package cn.demoframe.test.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Function {
	private static final Logger logger = LoggerFactory.getLogger(Thread
			.currentThread().getStackTrace()[1].getClassName());
	
    public synchronized static long getLongID(){
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
        } 
        Date d=new Date();
		return d.getTime();
    }
    
	public static String dealNull(Object str) {
		if (str == null || ((String) str).length() == 0)
			return "";
		else
			return (String) str;
	}

    public static String getCoordinate(String coor){
        Pattern pattern = Pattern.compile("[0-9]{1,9}.[0-9]{1,9}");
        Matcher matcher = pattern.matcher(coor);
        if (matcher.find()){
            return matcher.group();
        }
        return coor;
    }

	/**
	 * 是否是json字符串
	 * @param str 字符串
	 * @return 结果
	 */
    public static boolean isValidJson(String str) {
        try {
            return JSON.parse(str) != null;
        } catch (Exception e) {
            return false;
        }
    }
    
    public static boolean VerifyMacAddr(String mac) {
        Pattern pattern = Pattern.compile("[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}");
        Matcher matcher = pattern.matcher(mac);
		return matcher.find() && matcher.group().length() == mac.length();
	}

    public static boolean VerifyDateTime(String time) {
        Pattern pattern = Pattern.compile("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}");
        Matcher matcher = pattern.matcher(time);
		return matcher.find() && matcher.group().length() == time.length();
	}

    public static boolean VerifyDate(String Date) {
        Pattern pattern = Pattern.compile("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}");
        Matcher matcher = pattern.matcher(Date);
		return matcher.find() && matcher.group().length() == Date.length();
	}
    
    /**
	 * 判断是否为手机号码
	 * */
	public static boolean isTelphone(String str) {
		if (str == null) {
			return false;
		}
		
		Pattern p = Pattern.compile("^1\\d{10}$");
		Matcher match = p.matcher(str);  
		return match.matches();  
	}
	
	/**
	 * 是否全为数字
	 * */
	public static boolean isNumeric(String str) {
		if (str == null) {
			return false;
		}
		
		Pattern p = Pattern.compile("\\d*");
		Matcher match = p.matcher(str);  
		return match.matches();
	}
	
	/**
	 * 年校验
	 * YYYY
	 * */
	public static boolean VerifyYear(String year) {
        Pattern pattern = Pattern.compile("[0-9]{4}");
        Matcher matcher = pattern.matcher(year);
		return matcher.find() && matcher.group().length() == year.length();
	}
	
	/**
	 * 年月份校验
	 * YYYYMM
	 * */
	public static boolean VerifyMonth(String date) {
        Pattern pattern = Pattern.compile("[0-9]{4}-[0-9]{1,2}");
        Matcher matcher = pattern.matcher(date);
		return matcher.find() && matcher.group().length() == date.length();
	}
	
	/**
	 * 日期校验
	 * HH:mm
	 * */
	public static boolean VerifyTime(String time) {
        Pattern pattern = Pattern.compile("[0-9]{1,2}:[0-9]{1,2}");
        Matcher matcher = pattern.matcher(time);
		return matcher.find() && matcher.group().length() == time.length();
	}
	
	/**
	 * 校验时间是否正确
	 * 23:00 true
	 * 24:00 false
	 * 20150101 true
	 * 20150001 false
	 * */
	public static boolean timeValidate(String str, String pattern) {
		if(str == null || str.equals("")) {
			return false;
		}
		
		if(StringUtils.isEmpty(pattern)) {
			pattern = DateToolkit.YYYY_MM_DD_HH24_MM_SS;
		}
		
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			sdf.setLenient(false);
			
			Calendar calst = Calendar.getInstance(); // 起始时间
			calst.setTime(sdf.parse(str));
		} catch (ParseException e) {
			return false;
		}
		return true;
	}

	/**
	 * 解析XML
	 * @param xml xml
	 * @return 值
	 */
	public static String getResultValue(String xml, String key){
		String responseText = null;
		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			//字符串的形式读入
			InputStream in = new ByteArrayInputStream(xml.getBytes("UTF8"));
			org.w3c.dom.Document doc = db.parse(in);
 			XPath xpath = XPathFactory.newInstance().newXPath();
 			NodeList responseTextList = (NodeList)xpath.evaluate("//" + key, doc, XPathConstants.NODESET);
 			if(responseTextList != null && responseTextList.item(0) != null) {
 				responseText = responseTextList.item(0).getTextContent();
 			} else {
 				return null;
 			}
		} catch (Exception e) {
			logger.error("解析XML失败", e);
			return null;
		}
		return responseText;
	}

	/**
     * 把中文转成Unicode码 
     * @param str 字符串
     * @return 值
     */
	public static String chinaToUnicode(String str){
		if(StringUtils.isEmpty(str)) {
			return str;
		}
		String result="";
		for (int i = 0; i < str.length(); i++){
			int chr1 = str.charAt(i);
			result+="\\u" + Integer.toHexString(chr1);
		}
		return result;
	}
    
    /**
     * unicode转为中文
     * */
	public static String unicodeToChinese(String theString) {
		if(StringUtils.isEmpty(theString)) {
			return theString;
		}
		StringBuilder string = new StringBuilder();
		String[] hex = theString.split("\\\\u");
	    for (int i = 1; i < hex.length; i++) {
	        // 转换出每一个代码点
	        int data = Integer.parseInt(hex[i], 16);
	        // 追加成string
	        string.append((char) data);
	    }
	    return string.toString();
	}

	/**
	 * 获取指定长度的随机字符串
	 */
	public static String genRandomNum(int len) {
		char[] str = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
		final int maxNum = str.length - 1;

		StringBuilder pwd = new StringBuilder("");
		for (int i = 0; i < len; i++) {
			pwd.append(str[(int) Math.round(Math.random() * maxNum)]);
		}
		return pwd.toString();
	}
}
